import { BadRequestException, Body, Controller, Get, Post, Query, UseFilters } from '@nestjs/common';
import { ApiBody, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
import { clone, isEmpty, isNil } from 'ramda';
import { HttpExceptionFilter } from 'src/core/filter/http-exception.filter';
import { User } from 'src/user/entities/user.entity';
import { UserService } from 'src/user/user.service';
import { CreateleaveAMessageDto, MessageRo } from './dto/message-board.dto';
import { MessageBoardService } from './message-board.service';

@ApiTags('留言板')
@Controller('messageboard')
export class MessageBoardController {
  constructor(private readonly messageBoardService: MessageBoardService, private readonly userService: UserService) { }

  @Post('createleaveAMessage')
  @ApiQuery({
    description: '创建留言',
    type: CreateleaveAMessageDto,
  })
  @ApiBody({ description: '创建留言', type: CreateleaveAMessageDto })
  @ApiOperation({ summary: '创建留言', operationId: 'createleaveAMessage' })
  @UseFilters(new HttpExceptionFilter())
  async create(@Body() body: CreateleaveAMessageDto) {
    const { userId, toUserId, messageBoardId } = body
    const user = await this.userService.findOne(userId)
    let toUser: User
    if (!isNil(messageBoardId) && !isEmpty(messageBoardId)) {
      const users = await this.userService.findOne(toUserId)
      toUser = users
    }
    return await this.messageBoardService.create(body, { user, toUser })
  }

  @Get('/query')
  async findAll(
    @Query() query,
    @Query('pageSize') pageSize: number,
    @Query('pageNum') pageNum: number,
  ): Promise<MessageRo> {
    try {
      const data = await this.messageBoardService.findAll(query);
      const fatherList = []
      const sonList = []
      const sonListObj = {}

      for (const iterator of data.sonList) {
        const item = clone(iterator)
        const userInfo = await this.userService.findOne(item.userId)
        const toUserInfo = await this.userService.findOne(item.toUserId)
        const sonUserInfo = {
          id: userInfo.id,
          userName: userInfo.username || userInfo.nickname,
          avatar: userInfo.avatar
        }
        const obj = {
          ...item,
          toUserName: toUserInfo.username,
          userName: userInfo.username,
          userInfo: sonUserInfo
        }
        sonList.push(obj)

        const arr1 = sonListObj[item.parseId] ? sonListObj[item.parseId] : []
        arr1.push(obj)
        arr1.sort((a, b) => a.id - b.id);
        sonListObj[item.parseId] = arr1
      }
      //遍历父评论数组
      for (const iterator of data.list) {
        const item = clone(iterator)
        delete item.user
        const userInfo = await this.userService.findOne(item.userId)
        if (sonListObj[item.id]) {
          const twoMessageBoard = [...sonListObj[item.id]]
          item.twoMessageBoard = twoMessageBoard
        } else {
          item.twoMessageBoard = []
        }
        const fatherUserInfo = {
          id: userInfo.id,
          userName: userInfo.username || userInfo.nickname,
          avatar: userInfo.avatar
        }
        fatherList.push({ ...item, userName: userInfo.username, userInfo: fatherUserInfo })
      }
      data.list = fatherList
      data.count = fatherList.length
      return { list: data.list, count: data.count }
    } catch (error) {
      throw new BadRequestException(error.message);
    }
  }
}

